// @flow
import * as qiniu from 'qiniu-js'
import Service from './business/service/base.service'
import { config, ui, request } from './business/index'
import randomString from './randomString'
export default class BoqiiCDN extends Service {
  constructor () {
    super()
    this.qiniuDomain = this._getQiniuDomain()[config.env]
    this.baseUrl = this._getUptokenUrl()
    this.qiniu = qiniu
  }
  /**
   * 获取domain url配置.
   */
  _getQiniuDomain() {
    const domain = {
      dev: 'https://api-dev.boqiicdn.com',
      gqc: 'https://api-dev.boqiicdn.com',
      prd: 'https://api.boqiicdn.com'
    }
    return domain
  }
  /**
   * 获取uptoken url配置.
   */
  _getUptokenUrl() {
    const upkoken = {
      dev: '//api-dev.boqii.com/',
      gqc: '//api-dev.boqii.com/',
      prd: '//api.boqii.com/'
    }
    return upkoken
  }
  __getUptoken() {
    return this.request(
      'qiniutoken/qiniu_upload_token',
      'GET',
      {}
    )
  }

  /**
   * 上传图片文件.
   * @param {*} files
   */
  uploaderFiles(files) {
    return this.__getUptoken()
      .then(res => {
        const token = res.uptoken
        const domain = this.qiniuDomain
        const config = {
          useCdnDomain: true,
          disableStatisticsReport: false,
          retryCount: 5,
          region: qiniu.region.z0,
          qiniu_can_overwrite: true
        }
        const putExtra = { fname: '', params: {}, mimeType: null }

        return this.uploadWithSDK(files, token, putExtra, config, domain)
      })
      .catch(err => {
        console.log(err)
      })
  }

  /**
   * 上传base64图片文件到七牛云.
   * @param {*} baseImage
   */
  uploaderBase64ImageFiles(baseImage, header, loading = false) {
    const baseData = baseImage.split(',')[1]
    const url = `//upload.qiniup.com/putb64/${this.fileSize(baseData)}`
    const method = 'POST'
    return this.__getUptoken()
      .then(res => {
        const defaultHeader = {
          'Accept': 'application/json',
          'Content-Type': 'application/octet-stream',
          'Authorization': `UpToken ${res.uptoken}`
        }

        const finalData = Object.assign({}, {
          pic: baseData
        })
        const finalHeader = Object.assign(defaultHeader, header)

        Object.keys(finalData).forEach((key) => (finalData[key] == null) && delete finalData[key])
        Object.keys(finalHeader).forEach((key) => (finalHeader[key] == null) && delete finalHeader[key])

        if (loading) {
          ui.showLoading()
        }
        const promise = request.request(
          url,
          method,
          finalData,
          finalHeader,
          true
        )
        return this.unpackResponse(promise)
      })
  }
  /**
   * 上传图片到七牛云.
   * @param {*} files
   * @param {*} token
   * @param {*} putExtra
   * @param {*} config
   * @param {*} domain
   */
  uploadWithSDK(files, token, putExtra, config, domain) {
    ui.showLoading()

    return new Promise((resolve, reject) => {
      const observer = {
        next(res) {
          // ...
        },
        error(err) {
          ui.hideLoading()
          ui.showToast({
            duration: 3000,
            content: '文件上传出错'
          })
          reject(err)
        },
        complete(res) {
          // ...
          ui.hideLoading()
          const imagesUrl = qiniu.pipeline([], res.key, domain)
          resolve(imagesUrl)
        }
      }
      qiniu.createMkFileUrl(
        'https://up.qbox.me',
        files.size,
        files.name,
        putExtra
      )
      const string = randomString(8)
      const observable = qiniu.upload(files, `${string}${files.name}`, token, putExtra, config, domain)
      observable.subscribe(observer)
    })
  }
  /**
   * 计算base64图片文件大小.
   * @param {*} str
   */
  fileSize (str) {
    if (str.indexOf('=') > 0) {
      var indexOf = str.indexOf('=')
      str = str.substring(0, indexOf) // 把末尾的’=‘号去掉
    }

    return parseInt(str.length - (str.length / 8) * 2)
  }

  getImageUrl (key) {
    return qiniu.pipeline([], key, this.qiniuDomain)
  }

  getImageInfos (key) {
    return qiniu.imageInfo(key, this.qiniuDomain)
  }
}
